package com.police.db;

/**
 * Created by LEO on 13-6-6.
 */

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import java.util.ArrayList;
import java.util.List;

public class RelatedPeopleManager {
    private DBHelper helper;
    private SQLiteDatabase db;

    public RelatedPeopleManager(Context context) {
        helper = new DBHelper(context);
        //因为getWritableDatabase内部调用了mContext.openOrCreateDatabase(mName, 0, mFactory);
        //所以要确保context已初始化,我们可以把实例化DBManager的步骤放在Activity的onCreate里
        db = helper.getWritableDatabase();
    }

    /**
     * add RelatedPeoples
     *
     * @param RelatedPeoples
     */
    public void add(List<RelatedPeople> RelatedPeoples) {
        db.beginTransaction();    //开始事务
        try {
            for (RelatedPeople RelatedPeople : RelatedPeoples) {
                db.execSQL("INSERT INTO RelatedPeople VALUES(null, ?, ?, ?)", new Object[]{RelatedPeople.name, RelatedPeople.phoneNo, RelatedPeople.eventName});
            }
            db.setTransactionSuccessful();    //设置事务成功完成
        } finally {
            db.endTransaction();    //结束事务
        }
    }


    /**
     *
     * del event
     * @param eventName
     */
    public void del(String eventName){
        db.delete("RelatedPeople", "eventName = ?", new String[]{eventName});
    }
    /**
     * query all RelatedPeoples, return list
     *
     * @return List<RelatedPeople>
     */
    public List<RelatedPeople> query() {
        ArrayList<RelatedPeople> RelatedPeoples = new ArrayList<RelatedPeople>();
        Cursor c = queryTheCursor();
        while (c.moveToNext()) {
            RelatedPeople RelatedPeople = new RelatedPeople();
            RelatedPeople._id = c.getInt(c.getColumnIndex("_id"));
            RelatedPeople.name = c.getString(c.getColumnIndex("name"));
            RelatedPeople.phoneNo = c.getString(c.getColumnIndex("phoneNo"));
            RelatedPeople.eventName = c.getString(c.getColumnIndex("eventName"));
            RelatedPeoples.add(RelatedPeople);
        }
        c.close();
        return RelatedPeoples;
    }

    /**
     * query all RelatedPeoples, return cursor
     *
     * @return Cursor
     */
    public Cursor queryTheCursor() {
        Cursor c = db.rawQuery("SELECT * FROM RelatedPeople", null);
        return c;
    }

    /**
     * close database
     */
    public void closeDB() {
        db.close();
    }
}

